package backend

import (
	"blog/controllers/backend/api"
	"blog/library"
	"blog/models"
	"crypto/md5"
	"encoding/hex"
	"github.com/astaxie/beego"
	"strconv"
	"strings"
	"time"
)

type baseController struct {
	beego.Controller
	moduleName     string
	controllerName string
	actionName     string
	layout         string
}

type System struct {
	Year     int
	Version  string
	HomePage map[string]string
}

func (self *baseController) SystemInfo() {
	var system System
	t := time.Now()
	system.Year = t.Year()
	system.Version = "1.0.0"
	system.HomePage = map[string]string{"title": "首页", "href": "/"}
	self.Data["System"] = system
}

func (self *baseController) Prepare() {
	url := self.Ctx.Request.URL.String()
	var menuModel models.Menu
	menu, _ := menuModel.FindName(url)
	self.Data["Title"] = menu.MenuName
	self.Data["pageHeader"] = true
	controllerName, actionName := self.GetControllerAndAction()
	self.controllerName = strings.ToLower(controllerName[0 : len(controllerName)-10])
	self.actionName = library.CamelCase(actionName)
	moduleName := beego.AppConfig.String("layout")
	if moduleName == "" {
		moduleName = "backend"
	} else {
		menuList := library.MenuHtml(self.Ctx.Request.RequestURI)
		self.Data["Menu"] = menuList
	}

	self.layout = moduleName
	self.SystemInfo()
	self.moduleName = moduleName
}

//生成32位md5字串
func Md5(s string) string {
	h := md5.New()
	h.Write([]byte(s))
	return hex.EncodeToString(h.Sum(nil))
}

//加载模板
func (self *baseController) display(tpl ...string) {
	var tplName string
	if len(tpl) > 0 {
		tplName = self.moduleName + "/" + self.controllerName + "/" + strings.Join([]string{tpl[0], "html"}, ".")
	} else {
		tplName = self.moduleName + "/" + self.controllerName + "/" + self.actionName + ".html"
	}
	self.Layout = self.moduleName + "/" +
		"layout.html"
	self.TplName = tplName
}

func (self *baseController) notFound(messages ...string) {
	message := "很抱歉，你访问的页面找不到了"
	if len(messages) > 0 {
		message = messages[0]
	}
	self.baseError(message, 404)
}

func (self *baseController) serverError() {
	self.baseError("服务内部出现错误，请联系管理员", 500)
}

func (self *baseController) serverDbError() {
	self.baseError("数据库错误，请联系管理员", 500)
}

func (self *baseController) baseError(message string, code int) {
	self.Data["pageHeader"] = false
	if self.IsAjax() {
		var apiFormatter api.Api
		apiFormatter.Message = message
		apiFormatter.Code = code
		self.Data["json"] = apiFormatter
		self.ServeJSON()
		_ = self.Render()
		self.StopRun()
	} else {
		self.Layout = self.moduleName + "/" +
			"layout.html"
		codeArr := strconv.Itoa(code)
		total := len(codeArr)
		for i := 0; i < total; i++ {
			j := i + 1
			self.Data["errorCode"+strconv.Itoa(i)] = codeArr[i:j]
		}
		self.Data["errorMessage"] = message
		//self.TplName = self.moduleName + "/error/error.html"
		self.TplName = "backend/error/error.html"
		_ = self.Render()
		self.StopRun()
	}
}
